<template>
  <div>
    <!-- 从Vuex中判断用户是否已经登录-->
    <info-table v-if="user.isLoggedIn" :fixed="false" ref="InfoTable" :location="`details/operation/role/${user.info.role.id}`">
      <template slot="button-operation">
        <!-- 跳转到预处理模型管理页面,新建-->
        <b-button size="sm" variant="outline-primary" style="margin-right:6px" @click="createFaultAnticizateModel">
          新建模型
        </b-button>
      </template>
      <template slot="table-operation" slot-scope="row">
        <b-btn variant="outline-primary" style="margin-right:8px;padding:6px;font-size:0.7rem" @click="info(row.data)">信息</b-btn>
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="executeFaultAnticipateModelHandelOpen(row)">执行</b-btn>
        <!-- 修改操作也是跳转到预处理模型管理页面,不过是进行修改原有的数据 -->
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="alterFaultAnticipateModel(row)">修改</b-btn>
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="copyFaultAnticipateModelHandelOpen(row)">复制</b-btn>
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="deleteFaultAnticipateModelHandelOpen(row)">删除</b-btn>
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="branchManager(row)">分支管理</b-btn>
        <!-- 跳入历史管理界面 -->
        <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="historyFaultAnticipateModelManagerHandelOpen(row)">历史管理</b-btn>
      </template>
    </info-table>
    <!-- 执行按钮,运行故障预处理模型Modal -->
    <b-modal ref="ExecuteFaultAnticipateModel" title="请输入参数" size="lg" @hide="resultModelModalHide()">
      <b-container fluid>
        <div class="form">
          <!-- 重构时,将这部分内容写成一个组件 -->
          <b-alert v-if="executeFaultAnticipateModel.loading" show>正在获取模型的参数...</b-alert>
          <b-alert v-else-if="executeFaultAnticipateModel.items.length<1 && !executeFaultAnticipateModel.executing" show>没有输入参数</b-alert>
          <b-row v-else class="my-1" v-for="item in executeFaultAnticipateModel.items">
            <b-col sm="2">
              <label style="margin-botom:0px; margin-top:4px;"> {{ item.key }}:</label>
            </b-col>
            <b-col sm="7">
              <b-form-input style="width:auto;" size="sm" :disabled="executeFaultAnticipateModel.executing" v-model="item.value"></b-form-input>
            </b-col>
          </b-row>
        </div>
        <b-alert v-if="executeFaultAnticipateModel.executing" show>正在执行中,请不要关闭窗口...</b-alert>
        <b-alert v-else-if="executeFaultAnticipateModel.finish" show>执行完成</b-alert>
      </b-container>
      <div slot="modal-footer" class="w-100">
        <b-btn size="sm" class="float-right" variant="primary" @click="$refs.ExecuteFaultAnticipateModel.hide()" :disabled="executeFaultAnticipateModel.executing">
          返回
        </b-btn>
        <b-btn size="sm" class="float-right" style="margin-right:10px" variant="primary" :disabled="executeFaultAnticipateModel.loading||executeFaultAnticipateModel.executing" @click="executeModel()">
          执行预处理模型
        </b-btn>
      </div>
    </b-modal>
    <b-modal ref="CopyModelModal" title="复制模型" @ok="copyModelModalHandleOk">
      <b-container fluid>
        <form @submit.stop.prevent="copyModelModalHandleSubmit">
          <b-row class="my-1">
            <b-col sm="3">
              <label for="input-none">模型名称</label>
            </b-col>
            <b-col sm="9">
              <b-form-input type="text" v-model="copyModelModal.name" placeholder="新建模型"></b-form-input>
            </b-col>
          </b-row>
          <b-row class="my-1">
            <b-col sm="3">
              <label for="input-none">模型描述</label>
            </b-col>
            <b-col sm="9">
              <b-form-textarea v-model="copyModelModal.description" placeholder="模型描述" :rows="3" :max-rows="6">
              </b-form-textarea>
            </b-col>
          </b-row>
        </form>
      </b-container>
    </b-modal>
    <b-modal ref="ResultModelModal" title="模型操作结果" @hide="resultModelModalReset()" size="lg">
      <b-container fluid>
        <b-form-textarea id="textarea1" v-model="resultModelModal.output" placeholder="Enter something" :rows="3" :max-rows="6" disabled>
        </b-form-textarea>
      </b-container>
      <div slot="modal-footer" class="w-100">
        <b-btn size="sm" class="float-right" variant="primary" @click="$refs.ResultModelModal.hide()">
          返回
        </b-btn>
      </div>
    </b-modal>
    <b-modal ref="DeleteModelModal" title="删除模型" size="lg">
      <b-container fluid>
        确定删除?
      </b-container>
      <div slot="modal-footer" class="w-100">
        <b-btn size="sm" class="float-right" variant="primary" @click="$refs.DeleteModelModal.hide()">
          返回
        </b-btn>
        <b-btn size="sm" class="float-right" style="margin-right:10px" variant="primary" @click="remove(),$refs.DeleteModelModal.hide()">
          确定
        </b-btn>
      </div>
    </b-modal>
    <b-modal ref="FaultAnticipateModelHistoryModal" title="模型历史" size="lg">
      <b-container fluid>
        <FaultAnticipateModelHistoryListTable v-if="faultAnticipateModelHistoryModal.show" ref="ListTable" :currentDetail="currentDetail.data.item">
          <template slot="button-operation">
            <div></div>
          </template>
          <template slot="table-operation" slot-scope="row">
            <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="executeHistory(row)">执行历史</b-btn>
            <b-btn variant="outline-primary" style="margin:2px;padding:5px;font-size:0.7rem" @click="modelHistory(row)">模型历史</b-btn>
          </template>
        </FaultAnticipateModelHistoryListTable>
      </b-container>
      <div slot="modal-footer" class="w-100">
        <b-btn size="sm" class="float-right" variant="primary" @click="$refs.FaultAnticipateModelHistoryModal.hide()">
          返回
        </b-btn>
      </div>
    </b-modal>
    <InfoModal ref="DetailModal" v-on:update="$refs.InfoTable.refresh()" location="details"></InfoModal>
  </div>
</template>
<script>
/**
 * InfoTable
 * b-model * 5
 *
 *
 */
import _ from "lodash";
import FaultAnticipateModelHistoryListTable from "components/FaultAnticipateModelHistoryListTable.vue";
import {
  baseURL,
  get,
  save,
  associate,
  associateByPut,
  getAndAssociate,
  remove,
  update,
  axios
} from "src/service/api";
import { mapGetters } from "vuex";
import InfoTable from "@/components/InfoTable";
import InfoModal from "@/components/InfoModal.vue";
import websocket from "@/mixins/websocket";
// 故障预处理模型主要是对一些模型列表进行管理,对于模型本身的入参,处理,出参之类的操作是在FaultAnticipateModelManager中
export default {
  components: {
    InfoTable,
    InfoModal,
    FaultAnticipateModelHistoryListTable
  },
  mixins: [websocket],
  data() {
    return {
      table: {
        show: false,
        location: "",
        param: ""
      },
      currentRecord: {},
      currentDetail: {
        data: {
          item: {}
        }
      },
      currentModelId: "",
      executeFaultAnticipateModel: {
        loading: true,
        executing: false,
        finish: false,
        items: []
      },
      copyModelModal: {
        name: "",
        description: "",
        record: {}
      },
      faultAnticipateModelHistoryModal: {
        show: false,
        currentModel: {}
      },
      resultModelModal: {
        output: ""
      }
    };
  },
  created: function() {
    if (Notification.permission === "granted") {
      //console.log("用户允许通知");
    } else if (Notification.permission === "denied") {
      //console.log("用户拒绝通知");
    } else {
      //console.log("用户还没选择，去向用户申请权限吧");
    }
    Notification.requestPermission().then(function(permission) {
      if (permission === "granted") {
        //console.log("用户允许通知");
      } else if (permission === "denied") {
        //console.log("用户拒绝通知");
      }
    });
    // websocket 进行连接
    this.connect();
  },
  methods: {
    createFaultAnticizateModel() {
      const { href } = this.$router.resolve({
        path: "/fault-treatment/fault-anticipatie-model-manger"
      });
      window.open(href, "_blank");
    },
    resultModelModalReset() {
      this.resultModelModal = {};
      this.resultModelModal.output = "";
    },
    historyFaultAnticipateModelManagerHandelOpen(row) {
      this.currentDetail = row;
      this.faultAnticipateModelHistoryModal.show = true;
      this.$refs.FaultAnticipateModelHistoryModal.show();
    },
    alterFaultAnticipateModel(row) {
      this.currentDetail = row;
      const { href } = this.$router.resolve({
        path: "/fault-treatment/fault-anticipatie-model-manger",
        query: { entry: JSON.stringify(row.data.item), isMasterBranch: true }
      });
      window.open(href, "_blank");
    },
    modelHistory(row) {
      const { href } = this.$router.resolve({
        path: "/fault-treatment/fault-anticipatie-model-history-list",
        query: { entry: JSON.stringify(row.data.data.item) }
      });
      window.open(href, "_blank");
    },
    executeHistory(row) {
      const { href } = this.$router.resolve({
        path: "/fault-treatment/fault-anticipatie-model-history-manager",
        query: { entry: JSON.stringify(row.data.data.item) }
      });
      window.open(href, "_blank");
    },
    branchManager(row) {
      const { href } = this.$router.resolve({
        path: "/fault-treatment/fault-anticipatie-model-branch-manager",
        query: { entry: JSON.stringify(row.data.item) }
      });
      window.open(href, "_blank");
    },
    createFaultAnticipateModel() {
      const { href } = this.$router.resolve(
        "/fault-treatment/fault-anticipatie-model-manger"
      );
      window.open(href, "_blank");
    },
    remove: async function() {
      await remove(this.currentDetail.data.item._links.self.href)
        .then(function(response) {
          if (response.status == "204") {
            //console.log("资源删除成功");
          }
          console.log(response);
        })
        .catch(function(error) {
          //console.log(error);
        });
      this.$refs.InfoTable.refresh();
    },
    info(row) {
      this.$refs.DetailModal.info(row);
    },
    resultModelModalHide() {
      this.currentModelId = "";
      // 初始化
      this.executeFaultAnticipateModel = {
        executing: false,
        loading: true,
        finish: false,
        items: []
      };
    },
    executeModel: async function() {
      let self = this;
      // 正在运行操作懒加载
      this.executeFaultAnticipateModel.executing = true;
      let modelId = this.currentModelId;
      let detail = this.currentDetail.data.item;
      let operationId = -1;
      let operation;
      let data = {};
      this.executeFaultAnticipateModel.items.forEach(element => {
        data[element.key] = element.value;
      });
      // 进行运行操作
      await save(
        `models/operation/${this.getKey(detail._links.self.href)}/${modelId}`,
        {
          data: JSON.stringify(data)
        }
      )
        .then(response => {
          if (response.status == "200") {
            this.executeFaultAnticipateModel.executing = false;
            this.executeFaultAnticipateModel.finish = true;
            // 操作会返回操作的key
            operationId = response.data;
          }
          //console.log(response);
        })
        .catch(error => {
          //console.log(error);
          this.executeFaultAnticipateModel.executing = false;
          this.executeFaultAnticipateModel.finish = false;
        });
      await associateByPut(
        `operations/${operationId}/record`,
        `records/${this.currentRecord.id}`
      ).then(response => {
        if (response.status == "200") {
          console.log("关联成功");
        }
      });
    },
    executeFaultAnticipateModelHandelOpen: async function(row) {
      this.currentDetail = row;
      this.$refs.ExecuteFaultAnticipateModel.show();
      let model = await this.getModel(row.data.item);
      let data = JSON.parse(model.initParam);
      // 封装数据
      this.encapsulationRunData(data);
      this.executeFaultAnticipateModel.loading = false;
    },
    getModel: async function(detail) {
      let self = this;
      let key = parseInt(this.getKey(detail._links.self.href));
      let modelId;
      let model;
      //根据detail,获取主分支,获取最新record从而得到Model数据
      await save(`details/operation/model/${key}`)
        .then(response => {
          if (response.status == "200") {
            //console.log("资源record获取成功");
            this.currentRecord = response.data;
            modelId = this.currentRecord.modelId;
          }
          //console.log(response);
        })
        .catch(error => {
          //console.log(error);
        });
      await get(`models/${modelId}`)
        .then(response => {
          if (response.status == "200") {
            //console.log("资源model获取成功");
            model = response.data;
          }
          console.log(response);
        })
        .catch(error => {
          //console.log(error);
        });
      // 最后将当前模型的Id设置好,为后期的运行做准备
      this.currentModelId = modelId;
      return model;
    },
    encapsulationRunData(data) {
      let self = this;
      _.forEach(data, function(value, key) {
        if (value.indexOf("&&") != 0) {
          self.executeFaultAnticipateModel.items.push({
            key: key,
            value: value
          });
        }
        //  else {
        //   self.executeFaultAnticipateModel.items.push({
        //     key: key,
        //     value: value.substring(2, value.length)
        //   });
        // }
      });
    },
    getKey(str) {
      let position = str.lastIndexOf("/");
      return str.substring(position + 1, str.length);
    },
    //Method:copyModelModalClearParam 上传模型
    copyModelModalClearParam() {
      this.copyModelModal.name = "";
      this.copyModelModal.description = "";
    },
    copyModelModalHandleOk(evt) {
      // Prevent modal from closing
      evt.preventDefault();

      if (!this.copyModelModal.name) {
        alert("请输入名称");
      } else {
        this.copyModelModalHandleSubmit();
      }
    },
    copyFaultAnticipateModelHandelOpen(row) {
      this.currentDetail = row;
      //console.log(row.data.item);
      this.copyModelModal.name = row.data.item.name;
      this.copyModelModal.description = row.data.item.description;
      this.copyModelModal.record = row.data.item;
      this.$refs.CopyModelModal.show();
    },
    deleteFaultAnticipateModelHandelOpen(row) {
      this.currentDetail = row;
      this.$refs.DeleteModelModal.show();
    },
    copyModelModalHandleSubmit() {
      this.copyDetail(
        this.copyModelModal.record._links,
        this.copyModelModal.name,
        this.copyModelModal.description
      );
      this.copyModelModalClearParam();
      this.$refs.CopyModelModal.hide();
    },
    copyDetail: async function(href, name, description) {
      let self = this;
      let model;
      let detail;
      let record;
      let currentDetail = this.currentDetail.data.item;
      let detailKey = parseInt(this.getKey(currentDetail._links.self.href));
      let lastMaster;
      await save("details/operation/copy", {
        id: detailKey,
        name: name,
        description: description
      })
        .then(response => {
          if (response.status == "200") {
            alert("复制成功");
          }
          console.log(response);
        })
        .catch(error => {
          alert("复制失败,请检查命名是否重复");
          //console.log(error);
        });
    }
  },
  computed: {
    ...mapGetters(["user"])
  }
};
</script>
